<?php
/*
 * 函数文件
 * 1.1 全局性功能
 * 1.2 前台功能
 * 1.3 后台功能
*/
/**********************************************************
 * 1.1 全局性功能
 *
*/
//1.1.1防止回复按钮链接被搜索引擎重复抓取
add_filter('comment_reply_link', 'add_nofollow', 420, 4);
function add_nofollow($link, $args, $comment, $post){
  return preg_replace( '/href=\'(.*(\?|&)replytocom=(\d+)#respond)/', 'href=\'#comment-$3', $link );
}

//1.1.2禁用google字体，换成360字体库
function gamux_replace_open_sans() {
  wp_deregister_style('open-sans');
  wp_register_style( 'open-sans', '//fonts.useso.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600' );
  if(is_admin()) wp_enqueue_style( 'open-sans');
}

//1.1.3 禁止加载WP自带的jquery.js
if ( !is_admin() ) { // 后台不禁止
function my_init_method() {
wp_deregister_script( 'jquery' ); // 取消原有的 jquery 定义
}
add_action('init', 'my_init_method'); 
}
wp_deregister_script( 'l10n' );
add_action( 'init', 'gamux_replace_open_sans' );
//1.1.4 修改'编辑'用户的权限
function add_theme_caps(){
	$role = get_role( 'editor' );
	$role->remove_cap('manage_links');
	$role->remove_cap('delete_others_posts');
	$role->remove_cap('publish_pages');
}
add_action( 'admin_init', 'add_theme_caps' );
//1.1.5 非管理员访问'评论页面'则跳转
function gamux_restrict_admin() {
    if ( !current_user_can('level_10')  && $_SERVER['PHP_SELF'] == '/wp-admin/edit-comments.php' ) { //判断是否为管理员
        wp_redirect( '/10000/' ); //跳转到界面
    }
}
add_action( 'admin_init', 'gamux_restrict_admin', 1 );
//1.1.6 定义错误页面
/*
 *（1）404 错误页面
 *（2）10000 访问'评论'页面的跳转
 *
*/
/**********************************************************
 * 1.2 前台功能
 * 1.2.1 header和footer部分
 * 1.2.2 文章相关功能
 * 1.2.3 评论相关功能
*/
/*
 * 1.2.1 header和footer部分
*/
//1.2.1.1 移除不必要头部信息
//隐藏隐形显示的wordpress版本信息
remove_action( 'wp_head', 'wp_generator' );
//移除离线编辑器开放接口
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
//移除feed
remove_action( 'wp_head', 'feed_links', 2 );
remove_action( 'wp_head', 'feed_links_extra', 3 );
//移除无用url
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 ); 
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 ); 
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'wp_head', 'adjacent_posts_rel_link', 10, 0 ); 

//1.2.1.2 去掉顶部工具条
add_filter('show_admin_bar', '__return_false');

//1.2.1.3 重启友情链接
add_filter( 'pre_option_link_manager_enabled', '__return_true' );

//1.2.1.4 注册导航栏
register_nav_menus(array('header' => 'Gamux Menu'));

/*
 * 1.2.2 文章相关功能
*/
//1.2.2.1获取每篇文章第一张图片 
function catch_that_image() {
	global $post, $posts;
	$first_img = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	$first_img = $matches [1] [0];
	if(empty($first_img)){ //Defines a default image
		$popimg=get_option( '<img src="http://gamux.org/wp-content/uploads/2012/10/1326419858824.jpg">');
		$first_img = "$popimg";
	}
	return $first_img;
}

//1.2.2.2获取缩略图的src
function src_post_thumbnail() {
	if( has_post_thumbnail() ) {
		$img_id=get_post_thumbnail_id();
		$img_url=wp_get_attachment_image_src($img_id);
		$img_url=$img_url[0];
		return $img_url;
	}
}

//1.2.2.3获取指定分类的文章数量
function gamux_get_allfirst_posts($id) {
global $wpdb;
//获取二级分类的数组
	$sql1 = "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE $wpdb->term_taxonomy.parent = $id";
//去重后，计算二级分类所属游戏之和
	$sql2 = "
	SELECT count(distinct(ID)) from $wpdb->term_relationships join wp_posts on $wpdb->term_relationships.object_id = $wpdb->posts.ID WHERE $wpdb->term_relationships.term_taxonomy_id in ( $sql1 ) and $wpdb->posts.post_status = 'publish' 
	";
	return $wpdb->get_var($sql2);
}
//1.2.2.4 获取文章别名，本站将其作为文章英文名
function gamux_post_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug;
}
//1.2.2.5 获取文章中图片
function gamux_get_post_images($post_content, $sort=0){
	if($sort == 0){
    preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', do_shortcode($post_content), $matches);
		if($matches){     
			return $matches;//自行var_dump($matches)就可以看到效果了。
		}else{
			return false;
		}
	}else if($sort == 1){
    preg_match_all('|<video.*?src=[\'"](.*?)[\'"].*?>|i', do_shortcode($post_content), $matches);
		if($matches){     
			return $matches;//自行var_dump($matches)就可以看到效果了。
		}else{
			return false;
		}	
	}else {
		return false;
	}	
}
//1.2.2.6 设置文章浏览次数，然后调用显示热门文章
/*---------设置浏览次数-----------*/
//获取浏览数-参数文章ID   
function getPostViews($postID){   
    //字段名称   
    $count_key = 'post_views_count';   
    //获取字段值即浏览次数   
    $count = get_post_meta($postID, $count_key, true);   
    //如果为空设置为0   
    if($count==''){   
        delete_post_meta($postID, $count_key);   
        add_post_meta($postID, $count_key, '0');   
        return "0";   
    }   
    return $count;   
}   
//设置浏览数-参数文章ID   
function setPostViews($postID) {   
    //字段名称   
    $count_key = 'post_views_count';   
    //先获取获取字段值即浏览次数   
    $count = get_post_meta($postID, $count_key, true);   
    //如果为空就设为0   
    if($count==''){   
        $count = 0;   
        delete_post_meta($postID, $count_key);   
        add_post_meta($postID, $count_key, '0');   
    }else{   
        //如果不为空，加1，更新数据   
        $count++;   
        update_post_meta($postID, $count_key, $count);   
    }   
}
/*-----------设置浏览次数结束--------------*/
/*------------调用显示热门文章-------------*/

function gamux_get_hotpost($days=30,$post_num=16){
global $wpdb,$post;
//	date_default_timezone_set('PRC'); 设置时区为北京时间，本地调试和服务器在大陆时用
	$today = date("Y-m-d H:i:s");//获取今天日期时间
	$daysago = date("Y-m-d H:i:s", strtotime($today) - ($days * 24 * 60 * 60));
	$result = $wpdb->get_results("
		SELECT post_id,meta_key,meta_value,ID,post_title 
		FROM $wpdb->postmeta key1 
		INNER JOIN $wpdb->posts key2 ON key1.post_id = key2.ID 
		WHERE key2.post_type='post' 
		AND key2.post_status='publish' 
		AND key1.meta_key='post_views_count'
		AND key2.post_date BETWEEN '$daysago' AND '$today'
		ORDER BY CAST(key1.meta_value AS SIGNED) DESC LIMIT 0 , $post_num");

	foreach ($result as $post) {
	setup_postdata($post);
	$output .= '<li class="index-newgames-singal">
				<div class="index-games-thumb">
				<img src="'.src_post_thumbnail().'" alt="'.get_the_title().'" class="img-thumbnail">
				</div>
				<div class="index-games-title">
					<span><a href="'.wp_get_shortlink( $post->ID ).'">'.get_the_title().'</a></span>
				</div>
				<div class="index-games-view">
					<span>浏览次数：'.getPostViews(get_the_ID()).'</span>
				</div>
			  </li>';
	}
	return $output;
}
//1.2.2.7 取消自动加p
//remove_filter( 'the_content', 'wpautop' );
//1.2.2.8 分类模板设定每页显示文章数
add_action( 'pre_get_posts', 'get_one_post' );
function get_one_post( $query ) {
    if ( $query->is_category() && $query->is_main_query() ){
        $query->set( 'posts_per_page', 10 );
    }
}
//1.2.2.8 获取当前分类跟分类
function get_category_root_id($cat) {
	$this_category = get_category($cat); // 取得当前分类
	while($this_category->category_parent) {
		$this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类（往上爬）
	}
	return $this_category->term_id; // 返回根分类的id号
}

/*
 * 1.2.3 评论相关功能
*/

//1.2.3.1 自定义输出评论内容
function gamux_comment_option() {
	$GLOBALS['comment'] = $comments;
	$outopt = get_comment_meta($comment->comment_ID,'option',true);
/*	if($outopt == 'download') {
		return '[资源分享]';
	}else if($outopt == 'faq'){
		return '[问题互动]';
	}else if($outopt == 'evaluation') {
		return '[游戏测评]';
	}else {
		return '[老版评论]';
	}*/
	return $comments->comment_ID;
}
function gamux_comment($comment, $args, $depth) {   
$GLOBALS['comment'] = $comment; ?>
  
<li class="comment modal-content-hack <?php echo get_comment_meta($comment->comment_ID,'option',true); ?>" id="li-comment-<?php comment_ID(); ?>">
<div class="comments-title" role="tab" id="<?php echo '#heading'.get_comment_ID(); ?>">
  <a data-toggle="collapse" data-parent="#accordion" href="<?php echo '#comment-single-main'.get_comment_ID(); ?>" aria-controls="<?php echo 'comment-single-main'.get_comment_ID(); ?>">
	<span class="comment-single-sort">
		<?php  
			$outopt = get_comment_meta($comment->comment_ID,'option',true);
			if($outopt == 'download') {
				echo '[资源分享]';
			}else if($outopt == 'evaluation') {
				echo '[游戏测评]';
			}else {
				echo '[问题互动]';
			}
		?>
	</span>
	<span class="comment-single-title">
		<?php echo get_comment_meta($comment->comment_ID,'title',true); ?>
	</span>
	<span class="reply-count right">
	回复数量:<span class="reply-count-num"></span>
	</span>
  </a>
</div>
<?php //评论多了之后去掉in ?>
<div class="comments-main collapse in" id="<?php echo 'comment-single-main'.get_comment_ID(); ?>" aria-labelledby="<?php echo 'heading'.get_comment_ID(); ?>" role="tabpanel" aria-expanded="false">
	<div class="comment-author">
		<div class="comment-author-avatar">
			<?php echo get_avatar(disnametoid(get_comment_author()), '72', '','img-thumbnail'); ?>
		</div>

		<div class="comment-author-info">
		
		</div>
	</div>   
	<div class="comment-content" id="comment-<?php comment_ID(); ?>">
	  <div class="comment-content-body">
		<div class="comment-author-name">			
			<?php echo get_comment_author_link(); ?>
			<?php 
				if(disnametoid(get_comment_author()) == NULL) {
					echo '游客';
				}
				else if(disnametoid(get_comment_author()) == get_post()->post_author) {
					if(get_the_author_meta('user_level', disnametoid(get_comment_author())) == 10) {
						echo '(作者，站长)';
					}
					else if(get_the_author_meta('user_level', disnametoid(get_comment_author())) == 7) {
						echo '(作者，编辑 )';
					}
					else {
						echo '(作者，会员)';
					}
				}
				else {
					echo '(成员)';
				}
			?>
			<span class="user-vote">
			  <?php
				if(disnametoid(get_comment_author()) == NULL) {
					echo '';
				}
				else {
				 echo '评分：'.get_user_vote(disnametoid(get_comment_author()), get_the_ID()); 
				}
			  ?>
			</span>
		</div>
		<div class="comment-content-text">
			<?php if ($comment->comment_approved == '0') : ?>   
				<em>你的评论正在审核，稍后会显示出来！</em><br />   
			<?php endif; ?>   
			<?php comment_text(); ?>			
		</div>
	  </div>
		<div class="comment-content-info right">
			<span class="comment-content-date"><?php echo get_comment_time('Y-m-d H:i'); ?></span>
			<span class="comment-content-edit">
				<?php
					global $current_user;
					get_currentuserinfo();
					if( $current_user->display_name == get_comment_author_link() || current_user_can('level_10') ) {
						edit_comment_link('编辑');
					}
				?>
			</span>
			<span class="comment-content-reply">
				<?php if ($depth == get_option('thread_comments_depth')) : ?>
					 <a onclick="return addComment.moveForm( 'comment-<?php comment_ID() ?>','<?php echo $comment->comment_parent; ?>', 'respond','<?php echo $comment->comment_post_ID; ?>' )" href="?replytocom=<?php comment_ID() ?>#respond" class="comment-reply-link" rel="nofollow">回复</a>
				 <?php else: ?>
					 <a onclick="return addComment.moveForm( 'comment-<?php comment_ID() ?>','<?php comment_ID() ?>', 'respond','<?php echo $comment->comment_post_ID; ?>' ) " href="?replytocom=<?php comment_ID() ?>#respond" class="comment-reply-link" rel="nofollow">回复</a>
				 <?php endif; ?>				
			</span>
			<span class="comment-content-delete">
				<?php   
				if ( $current_user->user_ID == get_post()->post_author || current_user_can('level_10') ) {   
				$url = get_bloginfo('url');   
				echo '<a id="delete-'. $comment->comment_ID .'" href="' . wp_nonce_url("$url/wp-admin/comment.php?action=deletecomment&p=" . $comment->comment_post_ID . '&c=' . $comment->comment_ID, 'delete-comment_' . $comment->comment_ID) . '"" >删除</a>';   
				}   
				?>
			</span>
		</div>
	</div>
	<div class="clear"></div>


<?php }     
//1.2.3.2 评论添加"标题"和"选项"表单
function add_comment_title($comment_id) { 
    if(isset($_POST['title'])) {
        $title = wp_filter_nohtml_kses($_POST['title']);
		$option = wp_filter_nohtml_kses($_POST['option']);
        add_comment_meta($comment_id, 'title', $title, false);
		add_comment_meta($comment_id, 'option', $option, false);
    }
}
add_action ('comment_post', 'add_comment_title', 10, 1);

//1.2.3.3 添加ajax评论
require get_template_directory() . '/comments-do.php';
//1.2.3.4 获取用户归属地，根据ip判断
/*function getCity($ip) {
	$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
	$ip=json_decode(file_get_contents($url));
	if((string)$ip->code=='1'){ 
		return false; 
	} 
	$data = (array)$ip->data;
	return $data;
}
*/
//1.2.3.5 去掉"禁止重复评论"的限制,请慎用!!!
function enable_duplicate_comments_preprocess_comment($comment_data)
{
    //add some random content to comment to keep dupe checker from finding it
    $random = md5(time());
    $comment_data['comment_content'] .= " disabledupes{" . $random . "(本字符串会在刷新后消失^_^)"."}disabledupes";
    return $comment_data;
}
add_filter('preprocess_comment', 'enable_duplicate_comments_preprocess_comment');
function enable_duplicate_comments_comment_post($comment_id)
{
    global $wpdb;
    //remove the random content
    $comment_content = $wpdb->get_var("SELECT comment_content FROM $wpdb->comments WHERE comment_ID = '$comment_id' LIMIT 1");
    $comment_content = preg_replace("/disabledupes\{.*\}disabledupes/", "", $comment_content);
    $wpdb->query("UPDATE $wpdb->comments SET comment_content = '" . $wpdb->escape($comment_content) . "' WHERE comment_ID = '$comment_id' LIMIT 1");
    /*
        add your own dupe checker here if you want
    */
}
add_action('comment_post', 'enable_duplicate_comments_comment_post');
//1.2.3.6 获取文章的评论人数和评论数 by zwwooooo | zww.me 
function gamux_comment_user($postid=0,$which=0) {
	$comments = get_comments('status=approve&type=comment&post_id='.$postid); //获取文章的所有评论
	if ($comments) {
		$i=0; $j=0; $commentusers=array();
		foreach ($comments as $comment) {
			++$i;
			if ($i==1) { $commentusers[] = $comment->comment_author_email; ++$j; }
			if ( !in_array($comment->comment_author_email, $commentusers) ) {
				$commentusers[] = $comment->comment_author_email;
				++$j;
			}
		}
		$output = array($j,$i);
		$which = ($which == 0) ? 0 : 1;
		return $output[$which]; //返回评论人数
	}
	return 0; //没有评论返回0
}
//1.2.3.7 添加表情
function custom_smilies_src($src, $img){
	return get_bloginfo('template_directory').'/images/face/' . $img;
}
add_filter('smilies_src', 'custom_smilies_src', 10, 2);
//1.2.3.8 添加回复@
function gamux_comment_add_at( $comment_text, $comment = '') {
  if( $comment->comment_parent > 0) {
    $comment_text = '@<a href="#comment-' . $comment->comment_parent . '">'.get_comment_author( $comment->comment_parent ) . '</a> ' . $comment_text;
  }

  return $comment_text;
}
add_filter( 'comment_text' , 'gamux_comment_add_at', 20, 2);
//1.2.3.9 添加验证码
function spam_protection_math(){
//获取两个随机数, 范围0~9
$num1=rand(0,9);
$num2=rand(0,9);
//最终网页中的具体内容
echo "<label for='math' class='small' style='display: none;'> 验证码</label>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'>"
."$num1"."乘以"."$num2 =<input type='text' name='sum' class='math_textfield' value='' size='5'>";
 
}
function spam_protection_pre($commentdata){
$sum=$_POST['sum'];//用户提交的计算结果
switch($sum){
//得到正确的计算结果则直接跳出
case $_POST['num1']*$_POST['num2']:break;
//未填写结果时的错误讯息
case null:wp_die('错误: 请输入验证码.');break;
//计算错误时的错误讯息
default:wp_die('错误: 验证码错误,请重试.');
}
return $commentdata;
}
if((!is_user_logged_in()) && $comment_data['comment_type']==''){
add_filter('preprocess_comment','spam_protection_pre');
}

/**********************************************************
 * 1.3 后台功能
 * 
*/

//1.3.1 注册缩略图功能
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 125, 96, true );

//1.3.2 增加用户上传自定义头像功能
// 处理上传的头像
add_action('load-profile.php', array('bolo_avatar', 'load_profile_php'));
// 显示头像上传区域
add_action('show_user_profile', array('bolo_avatar', 'show_user_profile'));
// 使 get_avatar() 函数能优先显示用户上传的头像
add_filter('get_avatar', array('bolo_avatar', 'get_avatar'), 1, 5);
class bolo_avatar {
  function str_replace_once($needle, $replace, $haystack) {
    $pos = strpos($haystack, $needle);
    if($pos === false) {
      return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
  }

  // 把头像上传目录修改成 wp-contents/avatar
  function avatar_dir() {
    $siteurl = get_option('siteurl');
    $uploads['path'] = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'avatar';
    $uploads['url'] = content_url().'/avatar';
    $uploads['subdir'] = '';
    $uploads['basedir'] = $uploads['path'];
    $uploads['baseurl'] = $uploads['url'];
    $uploads['error'] = false;
    return $uploads;
  }

  function load_profile_php() {
    if($_SERVER['REQUEST_METHOD'] == 'POST' && $_FILES['avatar']['name'] && check_admin_referer('avatar-upload', '_wpnonce-avatar-upload')) {
      add_filter('upload_dir', array(__CLASS__, 'avatar_dir'));
      $user_id = (int)$_POST['user_id'];
      $overrides = array('test_form' => false);
      $uploaded_file = $_FILES['avatar'];
      $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'], false );
      $path_parts = pathinfo($uploaded_file['name']);
      $uploaded_file['name'] = $user_id.'_avatar.'.$path_parts['extension'];
      if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) )
        wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) );
  
      $file = wp_handle_upload($uploaded_file, $overrides);
      if ( isset($file['error']) )
        wp_die( $file['error'],  __( 'Image Upload Error' ) );

      $avatar_dir = self::avatar_dir();
      // 删除旧头像
      @unlink(str_replace(content_url(), WP_CONTENT_DIR, get_user_meta($user_id, 'avatar', true)));
      $image = wp_get_image_editor($file['file']);
      // 缩放头像
      $image->resize(96, 96);
      $image->save($file['file']);
      update_user_meta($user_id, 'avatar', $file['url']);
    }
    ob_start();
  }

  function show_user_profile($user) {
    $html = ob_get_clean();
    $html = str_replace('<form id="your-profile"', '<form id="your-profile" enctype="multipart/form-data"', $html);
    ob_start();
    ?>
    <tr>
      <th scope="row">头像</th>
      <td valign="middle">
        <?php echo get_avatar($user->ID); ?><br />
        <label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br />
        <input type="file" id="upload" name="avatar" />
        <?php wp_nonce_field('avatar-upload', '_wpnonce-avatar-upload'); ?>
      </td>
    </tr>
    <?php
    $avatar = ob_get_clean();
    $html = self::str_replace_once('<tr', $avatar.'<tr', $html);
    echo $html;
  }

  function get_avatar($avatar, $id_or_email, $size, $default, $class) {
    if(!is_numeric($id_or_email)) {
      return '<img alt="" src="http://www.gnu.org/graphics/heckert_gnu.small.png" class="'.$class.' avatar avatar-'.$size.' photo" height="'.$size.'" width="'.$size.'">';
    }else {
		$avatar_img = get_user_meta($id_or_email, 'avatar', true);
//    return $avatar_img?'<img alt="" src="'.$avatar_img.'" class="'.$class.' avatar avatar-'.$size.' photo" height="'.$size.'" width="'.$size.'">':$avatar;
		return '<img alt="" src="'.$avatar_img.'" class="'.$class.' avatar avatar-'.$size.' photo" height="'.$size.'" width="'.$size.'">';
	}
  }
}
//1.3.3后台添加信息模块
 

/* Use the admin_menu action to define the custom boxes */
add_action( 'add_meta_boxes', 'allfori_metabox' );

/* Use the save_post action to do something with the data entered */
add_action( 'save_post', 'allfori_metabox_save' );


function allfori_metabox() {

	// add_meta_box( $css-id, $title, $callback, $post_type, $context, $priority, $callback_args );
    add_meta_box( 'allfori_metabox', '添加信息', 
                'allfori_metabox_admin', 'post', 'side' );
    add_meta_box( 'allfori_metabox', '添加信息', 
                'allfori_metabox_admin', 'page', 'side' );
}
   
   
/* Prints the inner fields for the custom post/page section */
function allfori_metabox_admin() {

	global $montezuma, $post;
	wp_nonce_field( 'allfori_non', 'allfori_nonce' ); // Use nonce for verification
  	$thePostID = $post->ID;
	$post_id = get_post($thePostID);

	$version = get_post_meta( $post->ID, 'version', true );
	$website =  get_post_meta( $post->ID, 'website', true );
	$devcorp = get_post_meta( $post->ID, 'devcorp', true );
	$distrcorp = get_post_meta( $post->ID, 'distrcorp', true );
	$distrtime = get_post_meta( $post->ID, 'distrtime', true );
	$copyright = get_post_meta( $post->ID, 'copyright', true );
	$capacity = get_post_meta( $post->ID, 'copyright', true );//游戏容量
	$steam = get_post_meta( $post->ID, 'steam', true );
	
	$screen = get_current_screen();

	echo '
	<p>请注意，文章固定链接请改为游戏英文全名,steam钩子格式:http://store.steampowered.com/widget/xxx</p>
	<p>
		<label for="devcorp">开发公司</label>
		<input type="text" name="devcorp" id="devcorp" placeholder="小鸡家禽公司" value="'. $devcorp .'">
		<label for="distrcorp">发行公司</label>
		<input type="text" name="distrcorp" id="distrcorp" placeholder="小鸡家禽公司" value="'. $distrcorp .'">
	</p>
	<p>
		<label for="distrtime">发行时间</label>
		<input type="text" name="distrtime" id="distrtime" placeholder="2012年12月12日" value="'. $distrtime .'">
		<label for="website">官方网站(填写http地址)</label>
		<input type="text" name="website" id="website" placeholder="http://小鸡爱吃草.org" value="'. $website .'">
    </p>
	<p>
		<label for="version">最新版本</label>
		<input type="text" name="version" id="version" placeholder="1.56" value="'. $version .'">
		<label for="copyright">游戏版权(请填写BSD/GPL/闭源商业等)</label>
		<input type="text" name="copyright" id="copyright" placeholder="开源/GPL" value="'. $copyright .'">	
	</p>
	<p>
		<label for="capacity">游戏容量</label>
		<input type="text" name="capacity" id="capacity" placeholder="约1.5G" value="'. $capacity .'">
		<label for="steam">请填写steam钩子地址(iframe)</label>
		<input type="text" name="steam" id="steam" placeholder="http://store.steampowered.com/widget/20920/" value="'. $steam .'">		
	</p>
';
}

/* When the post is saved, save our custom data */
function allfori_metabox_save( $post_id ) {

	// verify if this is an auto save routine. 
	// If it is our form has not been submitted, so we dont want to do anything
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
		return;

	$mynonce = isset( $_POST['allfori_nonce'] ) ? $_POST['allfori_nonce']: '';
	if ( ! wp_verify_nonce( $mynonce, 'allfori_non' ) ) 
		return $post_id;

	if ( 'page' == $_POST['post_type'] ) {
		if ( ! current_user_can( 'edit_page', $post_id ) )
			return $post_id;
	} else {
		if ( ! current_user_can( 'edit_post', $post_id ) )
			return $post_id;
	}

	update_post_meta( $post_id, 'version', $_POST['version'] );
	update_post_meta( $post_id, 'website', $_POST['website'] );
	update_post_meta( $post_id, 'devcorp', $_POST['devcorp'] );
	update_post_meta( $post_id, 'distrtime', $_POST['distrtime'] );
	update_post_meta( $post_id, 'copyright', $_POST['copyright'] );
	update_post_meta( $post_id, 'distrcorp', $_POST['distrcorp'] );
	update_post_meta( $post_id, 'capacity', $_POST['capacity'] );
	update_post_meta( $post_id, 'steam', $_POST['steam'] );
	
}
//根据display_name获得user_ID
function disnametoid($disname) {
global $wpdb;
$userID = "select ID from $wpdb->users where display_name='$disname'";
return $wpdb->get_var($userID);
}


// 获取当前页面完整URL
function current_URL() 
{
     $pageURL = 'http';
 
    if ($_SERVER["HTTPS"] == "on") 
    {
         $pageURL .= "s";
     }
     $pageURL .= "://";
 
    if ($_SERVER["SERVER_PORT"] != "80") 
    {
         $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
     } 
    else 
    {
         $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
     }
     return $pageURL;
 }


//获取游戏所属所有父分类，分类之间用空格分开
function get_all_category() {
	$category = get_the_category();
	$a = count($category);
	if($a <= 1){
	  return $category[0]->cat_name;
	}
	else {
	  for($i=0;$i<($a-1);$i++){
		$output .= $category[$i]->cat_name.' ';
	  }
	$output = $output.$category[$a-1]->cat_name;
	return $output;
	}
}

/*---------------------------------------文章评分模块----------------------------------------------------------*/
/*********更新重写规则***************/    
function ashu_load_theme() {     
    global $pagenow;     
    if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )     
        ashu_vote_install(); //激活主题的时候执行函数     
}     
add_action( 'load-themes.php', 'ashu_load_theme' );     
function ashu_vote_install(){     
    global $wpdb;     
    //创建 _post_vote表     
    $table_name = $wpdb->prefix . 'post_vote';     
    if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :     
    $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` ( 
      `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,   
      `user` INT NOT NULL ,   
      `post` INT NOT NULL ,   
      `rating` varchar(10),   
      `ip` varchar(40)   
     ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";     
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');     
        dbDelta($sql);     
    endif;     
}    
/*   
*添加投票函数   
*$post_id 文章id   
*$user_id 用户ID   
*$ip 用户IP   
*$rating 投票内容   
*/    
function add_vote($post_id,$user_id='',$ip='',$rating='up'){     
    global $wpdb;     
    $user_id = (int)$user_id;     
    $post_id = (int)$post_id;     
    if(($user_id=='')&&($ip=='')){     
        return "e"; //返回error     
    }     
    //检查用户对某一文章是否已经投票票了     
    if($user_id!=''){     
        $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";     
    }else{     
        if($ip!=''){     
            $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";     
        }     
    }     
    $coo = $wpdb->get_results($check);          
    //如果不存在数据     
    if(!count($coo) > 0){     
        //插入数据 sql     
        $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";     
        $wpdb->query($s);     
        return "y"; //返回yes     
    }else{     
        return "h"; //返回have     
    }     
    return "e";//返回error     
}    
    /*    
    *获取文章投票数据    
    *$post_id 文章ID    
    *$vote 投票内容    
    */
//获取每个分数段的评分人数	
function get_post_vote($post_id,$vote){     
    global $wpdb;     
	$post_id = (int)$post_id;     
   //查询数据sql     
	$sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";     
	$coo = $wpdb->get_var($sql);     
	return $coo;
}
//获取指定文章平均评分	
function get_ave_post(){
	if($_POST['action'] == 'ave_num'){	
		global $wpdb;
		$post_id = $_POST['gameid'];
		$sqlnum = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id'";
		$sql5 = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='up'";
		$sql4 = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='subup'";
		$sql3 = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='mid'";
		$sql2 = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='subdown'";
		$sql1 = "select count(rating) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='down'";
		if($wpdb->get_var($sqlnum) == 0){
			echo '暂无评分';
			exit;
		}
		else{
			$output = ($wpdb->get_var($sql1)*1+$wpdb->get_var($sql2)*2+$wpdb->get_var($sql3)*3+$wpdb->get_var($sql4)*4+$wpdb->get_var($sql5)*5)/($wpdb->get_var($sqlnum));
			echo round($output, 1);
			exit;
		}		
	}
exit;
}	
add_action("wp_ajax_ave_num", "get_ave_post");     
add_action("wp_ajax_nopriv_ave_num", "get_ave_post");
//获取指定用户对指定文章的评分 
function get_user_vote($yonghu,$youxi) {
	global $wpdb;
	$sql = "select rating from ".$wpdb->prefix."post_vote where user='$yonghu' and post='$youxi'";
	$output = $wpdb->get_var($sql);
	switch ($output) {
		case 'up':
			return '5分';
			break;
		case 'subup':
			return '4分';
			break;
		case 'mid':
			return '3分';
			break;
		case 'subdown':
			return '4分';
			break;
		case 'down':
			return '1分';
			break;
		default:
			return '暂未评分';
	}
}	
/*    
*wp的ajax都可以通过请求中的action参数来执行对应的钩子    
*示例中我们的action参数值是vote_post    
*所以我们可以直接用下面两个钩子来执行动作    
*/     
add_action("wp_ajax_vote_post", "add_votes_options");     
add_action("wp_ajax_nopriv_vote_post", "add_votes_options");     
function add_votes_options() {     
    
if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){     
    $postid = (int)$_POST['postid'];     
    if( !$postid ){     
        echo 'e'; //输出error     
        die(0);     
    }     
    //cookie中是否已经存在投票数据     
    $voted = $_COOKIE["smzdm_voted_".$postid];     
    if( $voted ){     
        echo 'h'; //输出have     
        die(0);     
    }     
    $ip = $_SERVER['REMOTE_ADDR'];//ip     
    $rating = $_POST['rating']; //投票内容     
    //判断用户是否登录     
    if(  is_user_logged_in() ){     
        global $wpdb, $current_user;     
        get_currentuserinfo();     
        $uid = $current_user->ID;     
    }else{     
        $uid='';     
    }     	
    //添加数据     
    $voted = add_vote($postid,$uid,$ip,$rating);     
    if($voted=='y'){     
        //设置cookie     
        setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');     
        echo 'y';//输出yes     
        die(0);     
    }     
    if($voted=='h'){     
        //设置cookie     
        setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');     
        echo 'h';     
        die(0);     
    }     
    if($voted=='e'){     
        echo 'n';//输出no     
        die(0);     
    }     
}else{     
    echo 'e';//输出eroor     
}     
die(0);     
}   
